package com.yiwan.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import com.yiwan.dao.UserDao;
import com.yiwan.entity.User;
import com.yiwan.service.UserService;


@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String	result="Wrong user name or password, try it again.";
		response.setContentType("text/html");   
        PrintWriter out=response.getWriter();     
         
		
        String user = request.getParameter("user");
		String pass = request.getParameter("pass");
		String res = "-1";
		int userId = 0;
		// ��ȡϵͳ��ҵ���߼����
		//AuctionManager auctionManager = (AuctionManager)getCtx().getBean("mgr");
		// ��֤�û���¼
		User uf = new User();
		uf.setUname(user);
		uf.setPassword(pass);
		UserDao ud = new UserDao();
		UserService us = new UserService(ud);
		try {
			res=us.isLogin(uf);
			if(!res.equals(""))
				userId = 3;
			else
				userId = -1;
		
		response.setContentType("text/html; charset=UTF-8");
		// ��¼�ɹ�
		if (userId > 0)
		{
			request.getSession(true).setAttribute("userId" , userId);
		}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		};
		try
		{
			// ����֤��userId��װ��JSONObject
			JSONObject jsonObj = new JSONObject()
				.put("result" , res);
			// �����Ӧ
			response.getWriter().println(jsonObj.toString());
		}
		catch (JSONException ex)
		{
			result=result+"   "+ex.toString();
		}
	}
}